package www.cskaoyan.com.dao;

import www.cskaoyan.com.bean.Dormitory;
import www.cskaoyan.com.dao.JDBCUtils.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DormitoryManagerDao {

    Connection connection;

    // 获取宿舍列表
    public List<Dormitory> getDormitoryList() throws SQLException {
        connection = ConnectionPool.getConnection();
        String sql = "select *  from `dormitory` ";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        List<Dormitory> list = new ArrayList<>();
        while (resultSet.next()){

            int id = resultSet.getInt(1);
            String dormitoryName  = resultSet.getString(2);
            String address = resultSet.getString(3);

            Dormitory classManager = new Dormitory(id, dormitoryName, address);
            list.add(classManager);
        }
        return list;
    }


    // 创建宿舍
    public void createDormitory(String address, String dormitoryName) throws SQLException {
        connection = ConnectionPool.getConnection();

        String sql = "insert into `dormitory` set  address = ? , dormitoryName = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, address);
        preparedStatement.setString(2, dormitoryName);
        preparedStatement.executeUpdate();

        return ;
    }

    // 删除宿舍
    public void deleteDormitory(int dormitoryId) throws SQLException {
        connection = ConnectionPool.getConnection();

        String sql = "delete from `dormitory` where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, dormitoryId);
        preparedStatement.executeUpdate();

        return ;
    }

    public void changeDormitory(int id, String address, String dormitoryName) throws SQLException {
        connection = ConnectionPool.getConnection();

        String sql = "update `dormitory` set  address = ? , dormitoryName = ? where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, address);
        preparedStatement.setString(2, dormitoryName);
        preparedStatement.setInt(3, id);
        preparedStatement.executeUpdate();

        return ;
    }
}
